package com.jz.netthings.analysis.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jz.netthings.analysis.bean.operManage.CollMacRuningStatus;
import com.jz.netthings.analysis.bean.operManage.QueryCollMacRuningStatusSupport;
import com.jz.netthings.analysis.mapper.CollMacRuningStatusMapper;
import com.jz.netthings.analysis.service.CollMacRuningStatusService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.appengine.baseData.JzMachine;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.JzMachineMapper;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.application.providerCollection.bean.ProviderCollection;
import com.jz.netthings.application.providerCollection.mapper.mysql.ProviderCollectionMapper;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.system.mapper.mysql.JyUserMapper;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 单采机运行状况综合统计表 服务实现类
 * </p>
 *
 * @author yangyunyun
 * @since 2019-07-24
 */
@Service
public class CollMacRuningStatusServiceImpl extends ServiceImpl<CollMacRuningStatusMapper, CollMacRuningStatus> implements CollMacRuningStatusService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    CollMacRuningStatusMapper collMacRuningStatusMapper;
    @Autowired
    ProviderCollectionMapper providerCollectionMapper;
    @Autowired
    ProviderInfoMapper providerInfoMapper;

    @Autowired
    JzMachineMapper jzMachineMapper;
    @Autowired
    JyUserMapper jyUserMapper;

    @Override
    public void loadCollMacRunningStatus(String date) throws AdscmSystemException {
        if (!AdscmBaseUtils.getInstance().isNotEmpty(date,null)){
            date = AdscmDateUtils.getNowOnlyDateFomat1(new Date());
        }
        Date zeroDate = AdscmDateUtils.parseDate(date);
        logger.info("构造【"+date+"】的单采机运行状况综合统计数据");

        String beginTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";

        Wrapper<JzMachine> macWrapper = new EntityWrapper<>();
        macWrapper.eq("state","1");
        macWrapper.orderBy("id",true);
        List<JzMachine> machines = jzMachineMapper.selectList(macWrapper);

        if (machines != null && machines.size()>0){
            for (JzMachine machine : machines) {

                Wrapper<ProviderCollection> collWrapper = new EntityWrapper<>();
                collWrapper.between("collectionDate",beginTime,endTime);
                collWrapper.eq("machineNo",machine.getCode());
                collWrapper.orderBy("installStartTime",true);
                List<ProviderCollection> collList = providerCollectionMapper.selectList(collWrapper);

                if (collList != null && collList.size()>0){
                    for (int i = 0;i<collList.size();i++) {

                        ProviderCollection collection = collList.get(i);
                        Long providerId = null;
                        try{
                            providerId = Long.parseLong(collection.getProviderNo());
                        }catch (Exception e){
                            logger.error("采浆记录无浆员ID",e);
                            continue;
                        }
                        CollMacRuningStatus collRun = new CollMacRuningStatus();
                        collRun.setProviderId(providerId);
                        collRun.setCollectionDate(zeroDate);

                        collRun = collMacRuningStatusMapper.selectOne(collRun);

                        boolean isInsert = false;
                        if (collRun == null){
                            collRun = new CollMacRuningStatus();
                            collRun.setProviderId(providerId);
                            collRun.setCollectionDate(zeroDate);
                            isInsert = true;
                        }else {
                            if (collRun.getIsCollEnd() != null && collRun.getIsCollEnd() == 1){
                                continue;
                            }
                        }

                        //在记录的献浆过程没有处理完之前，构造过程数据

                        collRun.setMacNum(machine.getCode());
                        collRun.setMacId(machine.getId());


                        ProviderInfo info = providerInfoMapper.selectById(providerId);
                        collRun.setCardId(info.getCardId());
                        collRun.setProviderName(info.getName());

                        String nurse = collection.getNurse();
                        if (AdscmBaseUtils.getInstance().isNotEmpty(nurse,null)){
                            JyUser jyUser = jyUserMapper.selectById(nurse);
                            if (jyUser != null){
                                collRun.setNurseId(jyUser.getId());
                                collRun.setNurseName(jyUser.getName());
                            }else {
                                collRun.setNurseId(Integer.parseInt(nurse));
                            }
                        }

                        //安装耗材
                        collRun.setInstallStartTime(collection.getInstallStartTime());
                        collRun.setInstallEndTime(collection.getInstallEndTime());

                        String tokenTime = null;
                        if (collection.getInstallTaken() != null){
                            try{
                                int installToken =  new Long(Math.round(collection.getInstallTaken() / 1000d)).intValue();
                                tokenTime = AdscmDateUtils.getInputSecondsOuptMin(installToken);
                                collRun.setInstallTakens(installToken);
                                collRun.setInstallTakensDesc(tokenTime);
                            }catch (Exception e){ }
                        }

                        //安装耗材后的空闲时间
                        collRun.setInstallSpaceStartTime(collection.getInstallEndTime());
                        collRun.setInstallSpaceEndTime(collection.getPunctureStartTime());

                        if (collection.getInstallEndTime() != null && collection.getPunctureStartTime() != null){
                            try{
                                Long installToken = (collection.getPunctureStartTime().getTime() - collection.getInstallEndTime().getTime()) / 1000;

                                tokenTime = AdscmDateUtils.getInputSecondsOuptMin(installToken.intValue());
                                collRun.setInstallSpaceTakens(installToken.intValue());
                                collRun.setInstallSpaceTakensDesc(tokenTime);
                            }catch (Exception e){ }
                        }

                        //穿刺
                        collRun.setPunctureStartTime(collection.getPunctureStartTime());
                        collRun.setPunctureEndTime(collection.getPunctureEndTime());

                        if(collection.getPunctureTaken() != null){
                            try{
                                int installToken = new Long(Math.round(collection.getPunctureTaken() / 1000d)).intValue();
                                tokenTime = AdscmDateUtils.getInputSecondsOuptMin(installToken);
                                collRun.setPunctureTakens(installToken);
                                collRun.setPunctureTakensDesc(tokenTime);
                            }catch (Exception e){ }
                        }

                        //采浆
                        collRun.setCollectionStartTime(collection.getStartTime());
                        collRun.setCollectionEndTime(collection.getEndTime());
                        if(collection.getCollTaken() != null){
                            try{
                                int installToken = new Long(Math.round(collection.getCollTaken() / 1000d)).intValue();
                                tokenTime = AdscmDateUtils.getInputSecondsOuptMin(installToken);
                                collRun.setCollectionTakens(installToken);
                                collRun.setCollectionTakensDesc(tokenTime);
                            }catch (Exception e){ }
                        }

                        //卸载耗材
                        collRun.setUninstallStartTime(collection.getUninstallStartTime());
                        collRun.setUninstallEndTime(collection.getUninstallEndTime());
                        if(collection.getUninstallTaken() != null){
                            try{
                                int installToken = new Long(Math.round(collection.getUninstallTaken() / 1000d)).intValue();
                                tokenTime = AdscmDateUtils.getInputSecondsOuptMin(installToken);
                                collRun.setUninstallTakens(installToken);
                                collRun.setUninstallTakensDesc(tokenTime);
                            }catch (Exception e){ }
                        }

                        //i等于0说明是今天这台机器第一采集是没得空闲时间的

                        if (i>0) {
                            try{
                                ProviderCollection collBefore = collList.get(i-1);
                                collRun.setSpaceStartTime(collBefore.getUninstallEndTime());
                                collRun.setSpaceEndTime(collection.getInstallStartTime());
                                Long installToken = (collection.getInstallStartTime().getTime() - collBefore.getUninstallEndTime().getTime()) / 1000;
                                tokenTime = AdscmDateUtils.getInputSecondsOuptMin(installToken.intValue());
                                collRun.setSpaceTakens(installToken.intValue());
                                collRun.setSpaceTakensDesc(tokenTime);
                            }catch (Exception e){ }

                        }
                        collRun.setSpaceSequence(i+1);

                        //采浆层数
                        collRun.setCollectionCycles(collection.getCycles());
                        //单采机上传文件名
                        collRun.setMLogId(collection.getMachineLogId());
                        //是否完成采浆
                        if ("1".equals(collection.getIsDeal())){
                            collRun.setIsCollEnd(1);
                        }else {
                            collRun.setIsCollEnd(0);
                        }

                        if (isInsert){
                            collMacRuningStatusMapper.insert(collRun);
                        }else {
                            collMacRuningStatusMapper.updateById(collRun);
                        }

                    }
                }



            }
        }

    }


    @Override
    public List<CollMacRuningStatus> selectCollMacRunningStatus(QueryCollMacRuningStatusSupport queryCmrsSupport) throws AdscmSystemException {

        logger.info("条件查询运行综合统计数据...");

        String nurseIdsStr = queryCmrsSupport.getNurseIdsStr();
        if (AdscmBaseUtils.getInstance().isNotEmpty(nurseIdsStr,null)){
            String[] split = nurseIdsStr.split(",");
            List<String> list = Arrays.asList(split);
            queryCmrsSupport.setNurseIds(list);
        }

        List<CollMacRuningStatus> list = collMacRuningStatusMapper.selectCollMacRunningStatus(queryCmrsSupport);

        return list;
    }
}
